#!/usr/bin/env node

/**
 * Vision Analyzer Setup Wizard
 * 引导用户完成项目初始配置的友好向导
 */

const fs = require('fs');
const path = require('path');
const readline = require('readline');

/**
 * Check if required dependencies are installed
 */
function checkDependencies() {
  const requiredPackages = ['ajv'];
  const nodeModulesPath = path.join(__dirname, '../node_modules');

  if (!fs.existsSync(nodeModulesPath)) {
    console.log('📦 Dependencies not found.');
    console.log('Please run: npm install');
    process.exit(1);
  }

  const missingPackages = requiredPackages.filter(pkg => {
    const pkgPath = path.join(nodeModulesPath, pkg);
    return !fs.existsSync(pkgPath);
  });

  if (missingPackages.length > 0) {
    console.log(`📦 Missing dependencies: ${missingPackages.join(', ')}`);
    console.log('Please run: npm install');
    process.exit(1);
  }
}

class SetupWizard {
    constructor() {
        this.projectRoot = path.resolve(__dirname, '..');
        this.rl = readline.createInterface({
            input: process.stdin,
            output: process.stdout
        });
    }

    /**
     * 显示欢迎信息
     */
    showWelcome() {
        console.log('\n🎉 欢迎使用 Vision Analyzer！');
        console.log('================================');
        console.log('Vision Analyzer 是一个强大的视觉分析工具，支持多种AI服务商。');
        console.log('这个向导将帮助您完成初始配置。\n');
    }

    /**
     * 异步询问用户输入
     */
    async question(query) {
        return new Promise(resolve => {
            this.rl.question(query, resolve);
        });
    }

    /**
     * 检查当前配置状态
     */
    checkConfigurationStatus() {
        try {
            const ConfigPathResolver = require('./lib/config/config-path-resolver');
            const ConfigManager = require('./config-manager');

            const pathResolver = new ConfigPathResolver();
            const configPath = pathResolver.getConfigFilePath();
            const configManager = new ConfigManager(this.projectRoot);

            const configExists = fs.existsSync(configPath);

            return {
                configPath,
                configExists,
                configManager
            };
        } catch (error) {
            console.error('❌ 检查配置状态失败:', error.message);
            return {
                configPath: null,
                configExists: false,
                configManager: null
            };
        }
    }

    /**
     * 显示配置状态
     */
    async showConfigurationStatus() {
        console.log('📋 检查当前配置状态...\n');

        const { configPath, configExists, configManager } = this.checkConfigurationStatus();

        if (!configPath) {
            console.log('❌ 无法确定配置文件路径');
            return false;
        }

        console.log(`📁 配置文件位置: ${configPath}`);

        if (!configExists) {
            console.log('⚠️  配置文件不存在');
            return false;
        }

        if (configManager) {
            try {
                const status = await configManager.getConfigurationStatus(false);

                if (status.isConfigured) {
                    console.log('✅ 配置完整且有效');
                    console.log(`🎯 当前服务商: ${status.currentProvider || '未设置'}`);
                    console.log(`🔧 已配置服务商: ${status.configuredProviders.join(', ') || '无'}`);
                    return true;
                } else {
                    console.log('⚠️  配置文件存在但需要配置API密钥');
                    if (status.placeholderIssues.length > 0) {
                        console.log('❌ 需要配置的API密钥:');
                        status.placeholderIssues.forEach(issue => {
                            console.log(`   • ${issue}`);
                        });
                    }
                    return false;
                }
            } catch (error) {
                console.log('⚠️  无法读取配置状态:', error.message);
                return false;
            }
        }

        return false;
    }

    /**
     * 显示服务商信息
     */
    showProviderInfo() {
        console.log('\n🌐 支持的AI服务商:');
        console.log('==================='');

        const providers = [
            {
                name: 'Moonshot (月之暗面)',
                description: '支持多轮对话的AI助手，提供强大的视觉理解能力',
                signupUrl: 'https://platform.moonshot.cn/',
                models: ['moonshot-v1-8k-vision-preview', 'moonshot-v1-32k-vision-preview', 'moonshot-v1-128k-vision-preview']
            },
            {
                name: '腾讯混元',
                description: '腾讯出品的混元大模型，适合中文场景，性能优秀',
                signupUrl: 'https://console.cloud.tencent.com/hunyuan',
                models: ['hunyuan-vision', 'hunyuan-t1-vision']
            },
            {
                name: '智谱AI (GLM)',
                description: '清华智谱AI的GLM系列模型，GLM-4.5v具有优秀的视觉理解能力',
                signupUrl: 'https://open.bigmodel.cn/',
                models: ['glm-4.5v']
            }
        ];

        providers.forEach((provider, index) => {
            console.log(`\n${index + 1}. ${provider.name}`);
            console.log(`   描述: ${provider.description}`);
            console.log(`   注册地址: ${provider.signupUrl}`);
            console.log(`   支持模型: ${provider.models.join(', ')}`);
        });
    }

    /**
     * 引导用户选择服务商
     */
    async chooseProvider() {
        console.log('\n🎯 请选择要配置的服务商:');
        console.log('1. Moonshot (月之暗面)');
        console.log('2. 腾讯混元');
        console.log('3. 智谱AI (GLM)');
        console.log('4. 跳过配置');

        const choice = await this.question('\n请输入选项 (1-4): ');

        switch (choice.trim()) {
            case '1':
                return 'moonshot';
            case '2':
                return 'tencent';
            case '3':
                return 'zai';
            case '4':
                return null;
            default:
                console.log('❌ 无效选项，请重新选择');
                return await this.chooseProvider();
        }
    }

    /**
     * 获取API密钥
     */
    async getApiKey(providerName) {
        const providerInfo = {
            moonshot: {
                name: 'Moonshot (月之暗面)',
                keyPrefix: 'sk-',
                keyPattern: /^sk-[a-zA-Z0-9]{20,}$/
            },
            tencent: {
                name: '腾讯混元',
                keyPrefix: 'sk-',
                keyPattern: /^sk-[a-zA-Z0-9]{20,}$/
            },
            zai: {
                name: '智谱AI (GLM)',
                keyPrefix: '',
                keyPattern: /^[0-9]+\.[a-zA-Z0-9]{30,}$/
            }
        };

        const info = providerInfo[providerName];

        console.log(`\n🔑 配置 ${info.name} API密钥:`);
        console.log(`如果您还没有API密钥，请先访问: ${this.getProviderSignupUrl(providerName)}`);

        while (true) {
            const apiKey = await this.question(`请输入 ${info.name} API密钥: `);

            if (!apiKey || apiKey.trim() === '') {
                console.log('❌ API密钥不能为空');
                continue;
            }

            const trimmedKey = apiKey.trim();

            // 基本格式验证
            if (info.keyPrefix && !trimmedKey.startsWith(info.keyPrefix)) {
                console.log(`⚠️  ${info.name} API密钥通常以 "${info.keyPrefix}" 开头`);
                const confirm = await this.question('是否继续使用此密钥? (y/n): ');
                if (confirm.toLowerCase() !== 'y') {
                    continue;
                }
            }

            if (trimmedKey.length < 20) {
                console.log('⚠️  API密钥长度似乎太短，请确认是否正确');
                const confirm = await this.question('是否继续使用此密钥? (y/n): ');
                if (confirm.toLowerCase() !== 'y') {
                    continue;
                }
            }

            return trimmedKey;
        }
    }

    /**
     * 获取服务商注册地址
     */
    getProviderSignupUrl(providerName) {
        const urls = {
            moonshot: 'https://platform.moonshot.cn/',
            tencent: 'https://console.cloud.tencent.com/hunyuan',
            zai: 'https://open.bigmodel.cn/'
        };
        return urls[providerName] || '#';
    }

    /**
     * 保存配置
     */
    async saveConfiguration(providerName, apiKey) {
        try {
            const { configManager } = this.checkConfigurationStatus();

            if (!configManager) {
                console.error('❌ 无法创建配置管理器');
                return false;
            }

            console.log('\n💾 保存配置...');

            const result = await configManager.configureProvider(providerName, apiKey, true);

            if (result.success) {
                console.log('✅ 配置保存成功');
                console.log(`🎯 已设置 ${result.provider} 为当前服务商`);
                console.log(`🔑 API密钥: ${result.apiKey}`);
                return true;
            } else {
                console.error('❌ 配置保存失败:', result.error);
                return false;
            }
        } catch (error) {
            console.error('❌ 保存配置时出错:', error.message);
            return false;
        }
    }

    /**
     * 验证配置
     */
    async validateConfiguration() {
        console.log('\n🔍 验证配置...');

        try {
            const { configManager } = this.checkConfigurationStatus();

            if (!configManager) {
                console.log('❌ 无法验证配置');
                return false;
            }

            const status = await configManager.getConfigurationStatus(true);

            if (status.apiValidation.validatedProviders.length > 0) {
                console.log('✅ 配置验证成功');
                status.apiValidation.validatedProviders.forEach(provider => {
                    console.log(`   • ${provider.name}: ${provider.modelCount}个模型可用`);
                });
                return true;
            } else {
                console.log('❌ 配置验证失败');
                if (status.apiValidation.invalidProviders.length > 0) {
                    status.apiValidation.invalidProviders.forEach(provider => {
                        console.log(`   • ${provider.name}: ${provider.error}`);
                    });
                }
                return false;
            }
        } catch (error) {
            console.log('⚠️  无法验证配置:', error.message);
            console.log('💡 这可能是由于网络问题或API密钥无效导致的');
            return false;
        }
    }

    /**
     * 显示完成信息
     */
    showCompletionMessage() {
        console.log('\n🎉 配置完成！');
        console.log('==============');
        console.log('✅ Vision Analyzer 已成功配置');
        console.log('💡 您现在可以运行以下命令:');
        console.log('   npm test          # 运行测试');
        console.log('   npm start         # 启动服务');
        console.log('   node index.js     # 直接运行');
        console.log('\n📚 更多信息请查看 README.md 文件');
    }

    /**
     * 显示跳过配置信息
     */
    showSkipMessage() {
        console.log('\n⏭️  已跳过配置');
        console.log('==============');
        console.log('💡 您可以稍后通过以下方式配置:');
        console.log('   1. 编辑配置文件');
        console.log('   2. 运行 node scripts/setup-wizard.js');
        console.log('   3. 使用 Web 配置界面');
        console.log('\n📝 配置文件位置:');

        const { configPath } = this.checkConfigurationStatus();
        if (configPath) {
            console.log(`   ${configPath}`);
        }
    }

    /**
     * 运行设置向导
     */
    async run() {
        try {
            this.showWelcome();

            // 检查当前配置状态
            const isConfigured = await this.showConfigurationStatus();

            if (isConfigured) {
                console.log('\n✨ 您的配置已经完整！');
                const reconfigure = await this.question('是否要重新配置? (y/n): ');
                if (reconfigure.toLowerCase() !== 'y') {
                    this.showCompletionMessage();
                    this.cleanup();
                    return;
                }
            }

            // 显示服务商信息
            this.showProviderInfo();

            // 选择服务商
            const providerName = await this.chooseProvider();

            if (!providerName) {
                this.showSkipMessage();
                this.cleanup();
                return;
            }

            // 获取API密钥
            const apiKey = await this.getApiKey(providerName);

            // 保存配置
            const saved = await this.saveConfiguration(providerName, apiKey);

            if (saved) {
                // 验证配置
                await this.validateConfiguration();
                this.showCompletionMessage();
            } else {
                console.log('\n❌ 配置失败，请检查您的输入并重试');
            }

        } catch (error) {
            console.error('\n❌ 设置向导执行失败:', error.message);
        } finally {
            this.cleanup();
        }
    }

    /**
     * 清理资源
     */
    cleanup() {
        if (this.rl) {
            this.rl.close();
        }
    }
}

// 如果直接运行此脚本
if (require.main === module) {
    // 检查依赖
    checkDependencies();

    const wizard = new SetupWizard();
    wizard.run().catch(error => {
        console.error('❌ 设置向导启动失败:', error);
        process.exit(1);
    });
}

module.exports = SetupWizard;